Scope in JavaScript refers to the context in which variables and functions are accessible. It determines the visibility and lifetime of these variables and functions.
let
or const
within a block
(e.g., inside curly braces {}
) are in the block scope and can only be accessed within that
block.Variables declared outside any function have global scope:
let globalVar = "I am global";
function showGlobalVar() {
console.log(globalVar); // Accessible here
}
showGlobalVar();
console.log(globalVar); // Accessible here too
Variables declared within a function have function scope:
function myFunction() {
let functionVar = "I am local to this function";
console.log(functionVar); // Accessible here
}
myFunction();
console.log(functionVar); // Error: functionVar is not defined
Variables declared with let
or const
within a block have block scope:
{
let blockVar = "I am block scoped";
console.log(blockVar); // Accessible here
}
console.log(blockVar); // Error: blockVar is not defined
JavaScript uses a scope chain to resolve variable references. If a variable is not found in the current scope, JavaScript looks up the scope chain to find it.
let outerVar = "I am outside";
function outerFunction() {
let innerVar = "I am inside";
function innerFunction() {
console.log(outerVar); // Accessible here
console.log(innerVar); // Accessible here
}
innerFunction();
}
outerFunction();
For more detailed information, you can check out resources like W3Schools and MDN Web Docs.